package com.fqyd.campustransaction.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fqyd.campustransaction.model.User;

/**
 * 拦截器
 */
public class LoginHandlerIntercepter extends HandlerInterceptorAdapter {

	private final Logger logger = LogManager.getLogger(getClass());

	private static final String[] IGNORE_URI = { "/index.do", "/login.do", "/logout.do", "/register.do", "/goods.do", "/goods_details.do", "/index_task.do", "/task.do", "/task_details.do", "/news.do", "/admin_login.do" };

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uri = request.getRequestURI();

		if ("/".equals(uri.substring(request.getContextPath().length()))) {
			response.setCharacterEncoding("UTF-8");
			response.sendRedirect("index.do");
			return false;
		}

		for (String s : IGNORE_URI) {
			if (uri.contains(s)) {
				return true;
			}
		}

		User user = (User) request.getSession().getAttribute("loguser");
		if (user == null) {
			logger.info("session已失效，请重新登录。");
			if (uri.contains("/admin_")) {
				response.setCharacterEncoding("UTF-8");
				response.sendRedirect("admin_login.do");
				return false;
			} else {
				response.setCharacterEncoding("UTF-8");
				response.sendRedirect("login.do");
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}
}